package scatter.interview.rest.interview.i4_socket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * Created by yangwei
 * Created at 2020/12/4 10:36
 */
public class SocketClient {


    public static void main(String[] args)
            throws IOException {
        // Passingnull to getByName() produces the
        // special"Local Loopback" IP address, for
        // testingon one machine w/o a network:
        InetAddress addr =
                InetAddress.getByName("127.0.0.1");
        //Alternatively, you can use
        // theaddress or name:
        //InetAddress addr =
        //   InetAddress.getByName("127.0.0.1");
        //InetAddress addr =
        //   InetAddress.getByName("localhost");
        System.out.println("addr = " + addr);
        Socket socket =
                new Socket(addr, SocketServer.PORT);
        // Guard everything in a try-finally to make
        // sure thatthe socket is closed:
        try {
            System.out.println("socket = " + socket);
            BufferedReader KeyIn = new BufferedReader(new InputStreamReader(System.in));
            BufferedReader in =
                    new BufferedReader(
                            new InputStreamReader(
                                    socket.getInputStream()));
            // Output isautomatically flushed
            // by PrintWriter:
            PrintWriter out =
                    new PrintWriter(
                            new BufferedWriter(
                                    new OutputStreamWriter(
                                            socket.getOutputStream())),true);
//        for(int i = 0; i < 10; i ++) {
//          out.println("howdy " + i);
//          String str = in.readLine();
//          System.out.println(str);
//        }
//        out.println("END");
            String str =null;
            while(true)
            {
                str = KeyIn.readLine();
                if("END".equals(str)){
                    break;
                }
                out.println(str);
                System.out.println("Server:"+in.readLine());


            }
        } finally{
            System.out.println("closing...");
            socket.close();
        }
    }
}
